{
  "cells": [
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "<table class=\"ee-notebook-buttons\" align=\"left\">\n",
        "    <td><a target=\"_blank\"  href=\"https://github.com/giswqs/earthengine-py-notebooks/tree/master/Tutorials/Keiko/remove_colors.ipynb\"><img width=32px src=\"https://www.tensorflow.org/images/GitHub-Mark-32px.png\" /> View source on GitHub</a></td>\n",
        "    <td><a target=\"_blank\"  href=\"https://nbviewer.jupyter.org/github/giswqs/earthengine-py-notebooks/blob/master/Tutorials/Keiko/remove_colors.ipynb\"><img width=26px src=\"https://upload.wikimedia.org/wikipedia/commons/thumb/3/38/Jupyter_logo.svg/883px-Jupyter_logo.svg.png\" />Notebook Viewer</a></td>\n",
        "    <td><a target=\"_blank\"  href=\"https://colab.research.google.com/github/giswqs/earthengine-py-notebooks/blob/master/Tutorials/Keiko/remove_colors.ipynb\"><img src=\"https://www.tensorflow.org/images/colab_logo_32px.png\" /> Run in Google Colab</a></td>\n",
        "</table>"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## Install Earth Engine API and geemap\n",
        "Install the [Earth Engine Python API](https://developers.google.com/earth-engine/python_install) and [geemap](https://geemap.org). The **geemap** Python package is built upon the [ipyleaflet](https://github.com/jupyter-widgets/ipyleaflet) and [folium](https://github.com/python-visualization/folium) packages and implements several methods for interacting with Earth Engine data layers, such as `Map.addLayer()`, `Map.setCenter()`, and `Map.centerObject()`.\n",
        "The following script checks if the geemap package has been installed. If not, it will install geemap, which automatically installs its [dependencies](https://github.com/giswqs/geemap#dependencies), including earthengine-api, folium, and ipyleaflet."
      ]
    },
    {
      "cell_type": "code",
      "metadata": {},
      "source": [
        "# Installs geemap package\n",
        "import subprocess\n",
        "\n",
        "try:\n",
        "    import geemap\n",
        "except ImportError:\n",
        "    print('Installing geemap ...')\n",
        "    subprocess.check_call([\"python\", '-m', 'pip', 'install', 'geemap'])"
      ],
      "outputs": [],
      "execution_count": null
    },
    {
      "cell_type": "code",
      "metadata": {},
      "source": [
        "import ee\n",
        "import geemap"
      ],
      "outputs": [],
      "execution_count": null
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## Create an interactive map \n",
        "The default basemap is `Google Maps`. [Additional basemaps](https://github.com/giswqs/geemap/blob/master/geemap/basemaps.py) can be added using the `Map.add_basemap()` function. "
      ]
    },
    {
      "cell_type": "code",
      "metadata": {},
      "source": [
        "Map = geemap.Map(center=[40,-100], zoom=4)\n",
        "Map"
      ],
      "outputs": [],
      "execution_count": null
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## Add Earth Engine Python script "
      ]
    },
    {
      "cell_type": "code",
      "metadata": {},
      "source": [
        "# Add Earth Engine dataset\n",
        "# Credits to: Keiko Nomura, Senior Analyst, Space Intelligence Ltd\n",
        "# Source: https://medium.com/google-earth/10-tips-for-becoming-an-earth-engine-expert-b11aad9e598b\n",
        "# GEE JS: https://code.earthengine.google.com/?scriptPath=users%2Fnkeikon%2Fmedium%3Aremove_colours \n",
        "\n",
        "point = ee.Geometry.Point([2.173487088281263, 41.38710609258852])\n",
        "Map.centerObject(ee.FeatureCollection(point), 11)\n",
        "\n",
        "# Select the least cloudy image in 2019\n",
        "image = ee.ImageCollection('COPERNICUS/S2_SR') \\\n",
        "  .filter(ee.Filter.calendarRange(2019, 2019, 'year')) \\\n",
        "  .filterBounds(point) \\\n",
        "  .sort('CLOUDY_PIXEL_PERCENTAGE', True) \\\n",
        "  .select(['B2', 'B3', 'B4', 'B8']) \\\n",
        "  .first()\n",
        "\n",
        "# print('Image used', image)\n",
        "\n",
        "Map.addLayer(image, {\n",
        "  'bands': ['B4', 'B3', 'B2'],\n",
        "  'min': 0,\n",
        "  'max': 2500\n",
        "}, 'RGB (True colours)')\n",
        "Map.addLayer(image, {\n",
        "  'bands': ['B3', 'B3', 'B3'],\n",
        "  'min': 0,\n",
        "  'max': 2500,\n",
        "  'gamma': 1.5\n",
        "}, 'Grey (base)')\n",
        "\n",
        "# ======= #\n",
        "#  Green  #\n",
        "# ======= #\n",
        "\n",
        "# Select areas with vegetation (higher NDVI)\n",
        "imageNDVI = image.normalizedDifference(['B8', 'B4']).rename('ndvi')\n",
        "veg = imageNDVI.gte(0.4)\n",
        "imageGreen = image.multiply(veg)\n",
        "imageGreen_vis = imageGreen.selfMask().visualize(**{\n",
        "  'bands': ['B4', 'B3', 'B2'],\n",
        "  'min': 0,\n",
        "  'max': 2500\n",
        "})\n",
        "# Increase the strength of colour green to highlight the vegetation\n",
        "Map.addLayer(imageGreen_vis, {\n",
        "  'min': [50, 0, 50],\n",
        "  'max': [255, 200, 255]\n",
        "}, 'Green', True)\n",
        "\n",
        "# ======= #\n",
        "#   Red   #\n",
        "# ======= #\n",
        "\n",
        "# Select areas with non-vegetation (lower NDVI) and non-water (NDVI>0)\n",
        "bare = ee.Image(0).where(imageNDVI.gt(0), 1).where(imageNDVI.gt(0.1), 0)\n",
        "imageRed = image.multiply(bare)\n",
        "imageRed_vis = imageRed.selfMask().visualize(**{\n",
        "  'bands': ['B4', 'B3', 'B2'],\n",
        "  'min': 0,\n",
        "  'max': 2500\n",
        "})\n",
        "# Increase the strength of colour red\n",
        "Map.addLayer(imageRed_vis, {\n",
        "  'min': [0, 50, 50],\n",
        "  'max': [255, 255, 255]\n",
        "}, 'Red', False)\n",
        "\n",
        "# ======== #\n",
        "#   Blue   #\n",
        "# ======== #\n",
        "\n",
        "# Select areas with higher Normalised Difference Water Index (NDWI)\n",
        "# You can also use nir band (use Otsu method to find a threshold)\n",
        "imageNDWI = image.normalizedDifference(['B3', 'B8']).rename('ndwi')\n",
        "water = imageNDWI.gte(0.2)\n",
        "imageBlue = image.multiply(water)\n",
        "imageBlue_vis = imageBlue.selfMask().visualize(**{\n",
        "  'bands': ['B4', 'B3', 'B2'],\n",
        "  'min': 0,\n",
        "  'max': 2500\n",
        "})\n",
        "# Increase the strength of colour blue to highlight the water\n",
        "Map.addLayer(imageBlue_vis, {\n",
        "  'min': [10, 10, 0],\n",
        "  'max': [255, 255, 200]\n",
        "}, 'Blue', False)\n",
        "\n",
        "# ======== #\n",
        "#  Export  #\n",
        "# ======== #\n",
        "\n",
        "# Export the image as a mosaic (e.g. green), or use blend()\n",
        "grey = image.multiply(veg.select('ndvi').lt(0.4))\n",
        "mosaicGreen = ee.ImageCollection([\n",
        "  imageGreen_vis.visualize(**{\n",
        "    'min': [50, 0, 50],\n",
        "    'max': [255, 200, 255]\n",
        "  }),\n",
        "  grey.selfMask().visualize(**{\n",
        "    'bands': ['B3', 'B3', 'B3'],\n",
        "    'min': 0,\n",
        "    'max': 2500,\n",
        "    'gamma': 1.5\n",
        "  }),\n",
        "]).mosaic()\n",
        "#Map.addLayer(mosaicGreen, {}, 'export')\n",
        "\n",
        "# Export.image.toDrive({\n",
        "#   'image': mosaicGreen,\n",
        "#   description: 'green',\n",
        "#   'region': point.buffer(10000).bounds(),\n",
        "#   crs: 'EPSG:3857',\n",
        "#   'scale': 10\n",
        "# })\n",
        "\n",
        "# Other examples\n",
        "population = ee.Image(\"WorldPop/GP/100m/pop/ESP_2019\")\n",
        "pop_vis = {\n",
        "  'min': 0.0,\n",
        "  'max': 200.0,\n",
        "  'opacity': 0.3,\n",
        "  'palette': ['0000C0', 'FFFF80', 'C00000'],\n",
        "}\n",
        "Map.addLayer(population, pop_vis, 'Population', False)\n",
        "\n",
        "collectionCO = ee.ImageCollection('COPERNICUS/S5P/NRTI/L3_CO') \\\n",
        "  .select('CO_column_number_density') \\\n",
        "  .filterDate('2019-01-01', '2019-12-31')\n",
        "\n",
        "CO_viz = {\n",
        "  'min': 0.031,\n",
        "  'max': 0.034,\n",
        "  'opacity': 0.3,\n",
        "  'palette': ['black', 'blue', 'purple', 'cyan', 'green', 'yellow', 'red']\n",
        "}\n",
        "\n",
        "Map.addLayer(collectionCO.mean(), CO_viz, 'Carbon Monoxide', False)\n",
        "\n",
        "# ============ #\n",
        "#  Topography  #\n",
        "# ============ #\n",
        "\n",
        "# Optional: add topography by computing a hillshade using the terrain algorithms\n",
        "elev = ee.Image('USGS/SRTMGL1_003')\n",
        "shade = ee.Terrain.hillshade(elev)\n",
        "\n",
        "greenTR = ee.ImageCollection([\n",
        "  imageGreen_vis.visualize(**{\n",
        "    'min': [50, 0, 50],\n",
        "    'max': [255, 200, 255]\n",
        "  }),\n",
        "  shade.visualize(**{\n",
        "    'bands': ['hillshade', 'hillshade', 'hillshade'],\n",
        "    'opacity': 0.3\n",
        "  }),\n",
        "]).mosaic()\n",
        "\n",
        "Map.addLayer(greenTR.mask(imageGreen_vis), {\n",
        "}, 'Green (with topography)', False)\n",
        "\n",
        "# Convert the visualized elevation to HSV, first converting to [0, 1] data.\n",
        "hsv = greenTR.divide(255).rgbToHsv()\n",
        "# Select only the hue and saturation bands.\n",
        "hs = hsv.select(0, 1)\n",
        "# Convert the hillshade to [0, 1] data, as expected by the HSV algorithm.\n",
        "v = shade.divide(255)\n",
        "# Create a visualization image by converting back to RGB from HSV.\n",
        "# Note the cast to byte in order to export the image correctly.\n",
        "rgb = hs.addBands(v).hsvToRgb().multiply(255).byte()\n",
        "Map.addLayer(rgb.mask(imageGreen_vis), {'gamma': 0.6}, 'Green (topography visualised)', False)"
      ],
      "outputs": [],
      "execution_count": null
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## Display Earth Engine data layers "
      ]
    },
    {
      "cell_type": "code",
      "metadata": {},
      "source": [
        "Map.addLayerControl() # This line is not needed for ipyleaflet-based Map.\n",
        "Map"
      ],
      "outputs": [],
      "execution_count": null
    }
  ],
  "metadata": {
    "anaconda-cloud": {},
    "kernelspec": {
      "display_name": "Python 3",
      "language": "python",
      "name": "python3"
    },
    "language_info": {
      "codemirror_mode": {
        "name": "ipython",
        "version": 3
      },
      "file_extension": ".py",
      "mimetype": "text/x-python",
      "name": "python",
      "nbconvert_exporter": "python",
      "pygments_lexer": "ipython3",
      "version": "3.6.1"
    }
  },
  "nbformat": 4,
  "nbformat_minor": 4
}